package com.warehouse.sys.realm;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.warehouse.sys.common.ActiverUser;
import com.warehouse.sys.common.Constast;
import com.warehouse.sys.domain.Permission;
import com.warehouse.sys.domain.User;
import com.warehouse.sys.service.PermissionService;
import com.warehouse.sys.service.RoleService;
import com.warehouse.sys.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class UserRealm extends AuthorizingRealm {
    @Autowired
    @Lazy
    /**使用lazy的原因在程序加载的时候userService的代理对象没有被加载进入IoC中
     * 但userService被加载进入IoC中所以使用的并不是代理对象，所以使用Lazy
     * * */
    private UserService userService;

    @Autowired
    @Lazy
    private PermissionService permissionService;
    @Autowired
    @Lazy
    private RoleService roleService;

    @Override
    public String getName() {
        return this.getClass().getSimpleName();
    }

    /**
     * 授权
     *
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        ActiverUser activerUser = (ActiverUser) principals.getPrimaryPrincipal();
        User user = activerUser.getUser();
        List<String> permissions = activerUser.getPermissions();
        if (user.getType()==Constast.USER_TYPE_SUPER){
            authorizationInfo.addStringPermission("*:*");
        }else {
            if (null!=permissions&&permissions.size()>0){
                authorizationInfo.addStringPermission(String.valueOf(permissions));
            }
        }
        return authorizationInfo;
    }

    /**
     * 认证
     *
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("loginname", token.getPrincipal().toString());
        User user = userService.getOne(queryWrapper);
        if (null != user) {
            ActiverUser activerUser = new ActiverUser();
            activerUser.setUser(user);
            //根据用户ID查询percode
            //查询所有菜单
            QueryWrapper<Permission> qw = new QueryWrapper<>();
            //设置只能查询菜单
            qw.eq("type", Constast.TYPE_PERMISSION);
            qw.eq("available", Constast.AVAILABLE_TRUE);

            //普通用户登录显示菜单
            //根据用户ID+角色+权限去查询
            Integer userId = user.getId();
            //获取用户ID根据用户ID查询角色ID
            List<Integer> rids = roleService.queryUserRoleIdsByUid(userId);
            Set<Integer> permissionIds = new HashSet<>();
            for (Integer rid : rids) {
                List<Integer> pids = roleService.queryRolePermissionIdsByRid(rid);
                permissionIds.addAll(pids);
            }
            List<Permission> list = new ArrayList<>();
            if (permissionIds.size() > 0) {
                qw.in("id", permissionIds);
                list = permissionService.list(qw);
            }

            ArrayList<String> percodes = new ArrayList<>();
            for (Permission permission : list) {
                percodes.add(permission.getPercode());
            }
            //放到
            activerUser.setPermissions(percodes);

            ByteSource credentialsSalt = ByteSource.Util.bytes(user.getSalt());
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(activerUser, user.getPwd(), credentialsSalt, this.getName());
            return info;
        }
        return null;
    }
}
